package configs

import (
	"fmt"
	"os"
	"strconv"
)

// Config 系统配置结构
type Config struct {
	App        AppConfig
	Server     ServerConfig
	Database   DatabaseConfig
	Redis      RedisConfig
	MongoDB    MongoDBConfig
	Kamailio   KamailioConfig
	FreeSWITCH FreeSWITCHConfig
	JWT        JWTConfig
	Monitoring MonitoringConfig
}

// AppConfig 应用配置
type AppConfig struct {
	Name    string
	Version string
	Environment string
}

// ServerConfig 服务器配置
type ServerConfig struct {
	Port        int
	Host        string
	Environment string
}

// DatabaseConfig 数据库配置
type DatabaseConfig struct {
	DSN          string
	MaxOpenConns int
	MaxIdleConns int
}

// RedisConfig Redis配置
type RedisConfig struct {
	Addr     string
	Password string
	DB       int
}

// MongoDBConfig MongoDB配置
type MongoDBConfig struct {
	URI      string
	Database string
}

// KamailioConfig Kamailio配置
type KamailioConfig struct {
	Host     string
	Port     int
	Username string
	Password string
}

// FreeSWITCHConfig FreeSWITCH配置
type FreeSWITCHConfig struct {
	Host     string
	Port     int
	Password string
	Enabled  bool
}

// JWTConfig JWT配置
type JWTConfig struct {
	SecretKey string
	ExpiresIn int // 过期时间(秒)
}

// MonitoringConfig 监控配置
type MonitoringConfig struct {
	Enabled bool
	Port    int
}

// LoadConfig 加载配置
func LoadConfig() *Config {
	environment := getEnv("SERVER_ENVIRONMENT", "development")
	return &Config{
		App: AppConfig{
			Name:        getEnv("APP_NAME", "callcenter-api"),
			Version:     getEnv("APP_VERSION", "1.0.0"),
			Environment: environment,
		},
		Server: ServerConfig{
			Port:        getEnvAsInt("SERVER_PORT", 8000),
			Host:        getEnv("SERVER_HOST", "0.0.0.0"),
			Environment: environment,
		},
		Database: DatabaseConfig{
			DSN:          getEnv("DATABASE_DSN", "root:password@tcp(localhost:3306)/callcenter?charset=utf8mb4&parseTime=True&loc=Local"),
			MaxOpenConns: getEnvAsInt("DATABASE_MAX_OPEN_CONNS", 100),
			MaxIdleConns: getEnvAsInt("DATABASE_MAX_IDLE_CONNS", 10),
		},
		Redis: RedisConfig{
			Addr:     getEnv("REDIS_ADDR", "localhost:6379"),
			Password: getEnv("REDIS_PASSWORD", ""),
			DB:       getEnvAsInt("REDIS_DB", 0),
		},
		MongoDB: MongoDBConfig{
			URI:      getEnv("MONGODB_URI", "mongodb://localhost:27017"),
			Database: getEnv("MONGODB_DATABASE", "callcenter"),
		},
		Kamailio: KamailioConfig{
			Host:     getEnv("KAMAILIO_HOST", "localhost"),
			Port:     getEnvAsInt("KAMAILIO_PORT", 5060),
			Username: getEnv("KAMAILIO_USERNAME", "admin"),
			Password: getEnv("KAMAILIO_PASSWORD", "password"),
		},
		FreeSWITCH: FreeSWITCHConfig{
			Host:     getEnv("FREESWITCH_HOST", "localhost"),
			Port:     getEnvAsInt("FREESWITCH_PORT", 8021),
			Password: getEnv("FREESWITCH_PASSWORD", "ClueCon"),
		},
		JWT: JWTConfig{
			SecretKey: getEnv("JWT_SECRET_KEY", "your-secret-key"),
			ExpiresIn: getEnvAsInt("JWT_EXPIRES_IN", 3600),
		},
		Monitoring: MonitoringConfig{
			Enabled: getEnvAsBool("MONITORING_ENABLED", true),
			Port:    getEnvAsInt("MONITORING_PORT", 9090),
		},
	}
}

// 辅助函数：获取环境变量，如果不存在则返回默认值
func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

// 辅助函数：获取整型环境变量
func getEnvAsInt(key string, defaultValue int) int {
	valueStr := getEnv(key, "")
	if value, err := strconv.Atoi(valueStr); err == nil {
		return value
	}
	return defaultValue
}

// 辅助函数：获取布尔型环境变量
func getEnvAsBool(key string, defaultValue bool) bool {
	valueStr := getEnv(key, "")
	if value, err := strconv.ParseBool(valueStr); err == nil {
		return value
	}
	return defaultValue
}

// 格式化DSN（用于日志等，隐藏敏感信息）
func (c *DatabaseConfig) MaskedDSN() string {
	// 这里可以实现DSN脱敏逻辑
	return fmt.Sprintf("***:***@tcp(***:3306)/%s", "callcenter")
}